package com.carsystem.controller;


import com.carsystem.config.TencentCos;
import com.carsystem.utils.MessageConstant;
import com.carsystem.utils.MyFileUtils;
import com.carsystem.utils.Result;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Set;


@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${file.upload.path}")
    private String path;

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private TencentCos tencentCos;

    @PostMapping("/upload")
    public Result upload(@RequestParam("imgFile") MultipartFile multipartFile){
        String upload = MyFileUtils.upload(multipartFile, path);
        if(upload!=null){
            //把上传的图片名称保存到redis中
            SetOperations<String, String> opsForSet = redisTemplate.opsForSet();
            opsForSet.add("UPLOAD_SET",upload);
            return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS,upload);
        }
        return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
    }

    @GetMapping("/clean")
    public String clean(){
        SetOperations<String, String> opsForSet = redisTemplate.opsForSet();

        //求两个集合的差集
        Set<String> difference = opsForSet.difference("UPLOAD_SET", "DB_SET");
        if (difference!=null && difference.size()>0){//说明有垃圾图片
            //遍历集合，逐个清理
            for (String pic : difference) {
                // 2021/11/04/pic_202111041003064862.jpg
                //创建文件对象
                File file = new File(path+pic);
                if (file.exists()){//文件存在
                    file.delete();//删除文件
                }
            }
        }
        //清空redis的数据
        redisTemplate.delete("UPLOAD_SET");
        redisTemplate.delete("DB_SET");
        return "yes";
    }

    @GetMapping("/downLoadExcel")
    public ResponseEntity<byte[]> downLoadExcel() throws IOException {
        //响应体内容
        //获取这个文件
        File file=new File("E:\\download\\dd成绩表.xlsx");
        //把文件读取到字节数组
        byte[] responseBody = FileUtils.readFileToByteArray(file);
        //头部信息
        HttpHeaders headers = new HttpHeaders();
        //设置响应类型   二进制的方式，代表可以下载所有的文件类型
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //设置弹框 设置文件名  浏览器不要utf-8  要ios-8859-1
        String newName = new String(file.getName().getBytes(StandardCharsets.UTF_8), "ISO_8859_1");
        headers.setContentDispositionFormData("attachment",newName);
        //响应体内容，头部信息，状态码
        return new ResponseEntity<>(responseBody,headers, HttpStatus.OK);
    }

    /**
     * 上传图片
     * @param avatar
     * @return
     */
    @PostMapping(value = "/avatarUpload")
    public Result uploadAvatar(@RequestParam("imgFile") MultipartFile avatar){
        return new Result(true,"上传成功",tencentCos.uploadAvatar(avatar));
    }

    /**
     * 删除图片
     * @param key
     * @return
     */
    @GetMapping(value = "/avatarDelete")
    public Result uploadAvatar(@RequestParam("key") String key){
        tencentCos.deleteAvatar(key);
        return new Result(true,"删除成功");
    }
}
